package cn.edu.nuc.onlinestore.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import cn.edu.nuc.onlinestore.vo.Goods;
import cn.edu.nuc.onlinestore.vo.Person;

public class GoodsUpdateutil {

	public boolean addGoods(String name, double price, int num, String info) {
		boolean t=false;
		File f=new File("D:\\store\\goods\\");
		int id=f.list().length;
		Goods g=new Goods(name, price, num, info,++id);
		System.out.println(g);
		
		File f1=new File("D:/store/goods/"+name+".db");
		if(f1.exists()){
			
			
			Goods g1=ObjectUtil_a(f1);
			g1.setInfo(info);
			g1.setName(name);
			g1.setNum(num);
			g1.setPrice(price);
			
		    t=ObjectUtil_b(f1,g1);
			
			
		}else{
			t=ObjectUtil_b(f1,g);
			
		}
		
		return t;
	}
	
	
	
	public boolean Remove(String name) {
		File f1=new File("D:/store/goods/"+name+".db");
		System.out.println(f1.exists());
		if(f1.exists()){
			System.out.println(f1.delete());
			return true;
		}
		return false;
	}
	
	
	public Goods ObjectUtil_a(File f){
		FileInputStream in = null;
		ObjectInputStream din = null;
		try {
			in = new FileInputStream(f);
			din=new ObjectInputStream(in);
			
			
			return (Goods)din.readObject();
			
		} catch (IOException | ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				in.close();
				din.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		return null;
	}
	
	public boolean ObjectUtil_b(File f,Goods g){
		FileOutputStream out;
		ObjectOutputStream dout;
		try {
			 out=new FileOutputStream(f);
			 dout=new ObjectOutputStream(out);
			 dout.writeObject(g);
			 dout.flush();
			 
			 out.close();
			 dout.close();
			 return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}



	
	

}
